package com.ruoyi.qywx.service;

import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.callback.txl.ExternalUserEncrypt;
import com.ruoyi.qywx.getway.api.MessageEventApi;
import com.ruoyi.qywx.getway.entity.QyWelcome;
import com.ruoyi.qywx.service.inters.ContactWayService;
import com.ruoyi.qywx.service.inters.PublicWelcomeService;
import com.ruoyi.qywx.service.inters.QyMessageEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author : hcl
 * @Date : 2023/8/22 14:45
 */
@Service
public class QyMessageEventServiceImpl implements QyMessageEventService {
    @Autowired
    private ContactWayService contactWayService;
    @Autowired
    private PublicWelcomeService publicWelcomeService;

    /**
     * 发送欢迎语
     */
    @Override
    public QyWelcome sendExternalWelcome(ExternalUserEncrypt encrypt, Meta meta) {
        if (StrUtils.isNotEmpty(encrypt.getWelcomeCode())) {
            QyWelcome welcome = contactWayService.findContactWayWelcome(encrypt.getState(), meta);
            if (Objects.isNull(welcome)) { // 全局欢迎语 兜底
                welcome = publicWelcomeService.findPublicWelcomByUserId(encrypt.getUserID(), meta);
            }
            if (Objects.nonNull(welcome)) { // 发送欢迎语
                welcome.getWelcome().put("welcome_code", encrypt.getWelcomeCode());
                MessageEventApi.sendExternalContactWelcome(meta, welcome.getWelcome());
                return welcome;
            }
        }
        return null;
    }
}
